<template>
  <div class="roles-container">
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片 -->
    <el-card>
      <!-- 添加角色按钮 -->
      <el-row>
        <el-col>
          <el-button type="primary" @click="showAddDialog">添加角色</el-button>
        </el-col>
      </el-row>
    </el-card>
    <!-- 添加角色对话框 -->
    <el-dialog
      title="提示"
      :visible.sync="addDialogVisible"
      width="50%"
      @closed="resetAddForm"
    >
      <el-form
        :model="addRole"
        :rules="addRoleRules"
        ref="addRoleRef"
        label-width="80px"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addRole.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述">
          <el-input v-model="addRole.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRoleInfo">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 角色列表 -->
    <el-table :data="rolesList" style="width: 100%">
      <!-- 展开列 -->
      <el-table-column type="expand">
        <template slot-scope="scope">
          <el-row
            :class="['line-bottom', index === 0 ? 'line-top' : '', 'vcenter']"
            v-for="(item, index) in scope.row.children"
            :key="item.id"
          >
            <!-- 渲染一级权限 -->
            <el-col :span="5">
              <el-tag closable @close="removeRightById(scope.row, item.id)">{{
                item.authName
              }}</el-tag>
              <i class="el-icon-caret-right"></i>
            </el-col>
            <!-- 渲染二级和三级权限 -->

            <el-col :span="19">
              <!-- 通过for循环渲染二级权限 -->
              <el-row
                :class="[index2 === 0 ? '' : 'line-top', 'vcenter']"
                v-for="(item2, index2) in item.children"
                :key="item2.id"
              >
                <el-col :span="6">
                  <el-tag
                    type="success"
                    closable
                    @close="removeRightById(scope.row, item2.id)"
                    >{{ item2.authName }}</el-tag
                  >
                  <i class="el-icon-caret-right"></i>
                </el-col>
                <el-col :span="18">
                  <!-- 通过for循环渲染三级权限 -->
                  <el-col>
                    <el-tag
                      v-for="item3 in item2.children"
                      :key="item3.id"
                      closable
                      @close="removeRightById(scope.row, item3.id)"
                    >
                      {{ item3.authName }}
                    </el-tag>
                  </el-col>
                </el-col>
              </el-row>
            </el-col>
          </el-row>
          <!-- <pre>
            {{ scope.row }}
          </pre> -->
        </template>
      </el-table-column>

      <!-- 索引列 -->
      <el-table-column type="index" label="#"> </el-table-column>
      <el-table-column prop="roleName" label="角色名称"> </el-table-column>
      <el-table-column prop="roleDesc" label="角色描述"> </el-table-column>
      <el-table-column prop="address" label="操作" width="300">
        <template slot-scope="scope">
          <el-button
            type="primary"
            icon="el-icon-edit"
            size="mini"
            @click="editRoleById(scope.row.id)"
            >编辑</el-button
          >
          <el-button
            type="danger"
            size="mini"
            icon="el-icon-delete"
            @click="deleteRoleById(scope.row.id)"
            >删除</el-button
          >
          <el-button
            type="warning"
            size="mini"
            icon="el-icon-setting"
            @click="showSetRightDialog(scope.row)"
            >分配权限
          </el-button>

          <!-- 分配权限对话框 -->
          <el-dialog
            title="分配权限"
            :visible.sync="setRightdialogVisible"
            width="30%"
            @close="resetCheckedArr"
          >
          <!-- Tree 树形控件 -->
            <el-tree :data="rightsList" :props="treeProps"
            show-checkbox
            node-key="id"
            default-expand-all
            :default-checked-keys="checkedArr"
            ref="rightTreeRef"
            >
            </el-tree>
            <span slot="footer" class="dialog-footer">
              <el-button @click="setRightdialogVisible = false">取 消</el-button>
              <el-button type="primary" @click="confirmSetRights"
                >确 定</el-button
              >
            </span>
          </el-dialog>
        </template>
      </el-table-column>
    </el-table>

    <!-- 编辑角色对话框 -->
    <el-dialog title="提示" :visible.sync="editDialogVisible" width="30%">
      <el-form :model="editRole" ref="editRoleRef" label-width="70px">
        <el-form-item label="角色ID">
          <el-input v-model="editRole.roleId" disabled></el-input>
        </el-form-item>
        <el-form-item label="角色名称">
          <el-input v-model="editRole.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述">
          <el-input v-model="editRole.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="changeRoleInfo">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    return {
      // 所有角色列表数据
      rolesList: [],
      // 编辑角色对象
      editRole: {},
      // 控制编辑角色对话框的显示与隐藏
      editDialogVisible: false,

      // 控制添加角色对话框的显示与隐藏
      addDialogVisible: false,
      // 添加角色对象
      addRole: {
        roleName: '',
        roleDesc: ''
      },
      // 添加角色规则对象
      addRoleRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' }
        ]
      },
      // 控制分配权限对话框的显示与隐藏
      setRightdialogVisible: false,
      // 所有权限列表
      rightsList: [],
      treeProps: {
        children: 'children',
        label: 'authName'
      },
      // 默认勾选的权限节点的 key 的数组
      checkedArr: [],
      // 当前分配权限的角色id
      roleId: ''
    }
  },
  created () {
    this.getRolesList()
  },
  methods: {
    // 获取所有角色列表数据
    async getRolesList () {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        return this.$message.error('获取角色列表失败')
      }
      this.rolesList = res.data
    },
    // 编辑角色
    // 根据id查询角色
    async editRoleById (id) {
      // console.log(id)
      const { data: res } = await this.$http.get('roles/' + id)
      if (res.meta.status !== 200) return this.$message.error('获取角色失败')
      this.editRole = res.data
      // console.log(this.editRole)
      this.editDialogVisible = true
    },

    // 提交角色的修改
    async changeRoleInfo () {
      const { data: res } = await this.$http.put(
        'roles/' + this.editRole.roleId,
        {
          roleName: this.editRole.roleName,
          roleDesc: this.editRole.roleDesc
        }
      )
      if (res.meta.status !== 200) return
      this.editDialogVisible = false
      this.$message.success('修改角色成功！')
      this.getRolesList()
    },

    // 删除角色
    async deleteRoleById (id) {
      const res = await this.$confirm(
        '此操作将永久删除该角色, 是否继续?',
        '删除角色',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
        .then(() => {
          return 'confirm'
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
          return 'cancel'
        })
      // 确认删除则发起删除请求
      if (res === 'confirm') {
        const { data: res } = await this.$http.delete('roles/' + id)
        if (res.meta.status !== 200) return
        this.$message.success('删除角色成功！')
        this.getRolesList()
      }
    },

    // 显示添加角色对话框
    showAddDialog () {
      this.addDialogVisible = true
    },

    // 添加角色
    async addRoleInfo () {
      // console.log(this.addRole)
      const { data: res } = await this.$http.post('roles', this.addRole)
      if (res.meta.status !== 201) return
      this.addDialogVisible = false
      this.$message.success('添加角色成功！')
      this.getRolesList()
    },
    // 添加角色对话框关闭时重置添加角色表单
    resetAddForm () {
      // 这里重置不起效？
      this.$refs.addRoleRef.resetFields()
    },
    // 根据id删除权限
    async removeRightById (role, rightid) {
      const confirmRes = await this.$confirm(
        '此操作将永久删除该权限, 是否继续?',
        '删除权限',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch((err) => err)
      if (confirmRes !== 'confirm') return this.$message.info('取消删除')
      // roles/:roleId/rights/:rightId
      const { data: res } = await this.$http.delete(
        'roles/' + role.id + '/rights/' + rightid
      )
      if (res.meta.status !== 200) return
      this.$message.success('取消权限成功')
      // this.getRolesList()  这样会刷新页面 不能保持权限展开的状态
      // 重新给角色的children属性赋值
      role.children = res.data
    },
    // 显示分配权限对话框
    async showSetRightDialog (role) {
      // 将当前角色保存起来
      this.roleId = role.id
      // 调用API 所有权限列表
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) return this.$message.error('获取所有权限失败')
      this.rightsList = res.data
      // 递归获取所有三级权限的id
      this.getLeafKeys(role, this.checkedArr)
      this.setRightdialogVisible = true
    },
    // 通过递归的形式 获取所有三级权限的id 并保存到checkedArr中
    getLeafKeys (node, arr) {
      if (!node.children) {
        return arr.push(node.id)
      }
      node.children.forEach(item => {
        this.getLeafKeys(item, arr)
      })

      // console.log(arr)
    },
    // 当关闭分配权限对话框时 重置当前角色的权限默认选中数组
    resetCheckedArr () {
      this.checkedArr = []
    },
    // 分配权限对话框点击确定按钮时触发
    async confirmSetRights () {
      const arr = [...this.$refs.rightTreeRef.getCheckedKeys(),
        ...this.$refs.rightTreeRef.getHalfCheckedKeys()]
      const keysStr = arr.join(',')
      // console.log(keysStr)
      // 调用API 角色授权
      const { data: res } = await this.$http.post('roles/' + this.roleId + '/rights', {
        rids: keysStr
      })
      if (res.meta.status !== 200) return this.$message.error('分配权限失败')
      this.getRolesList()
      this.$message.success('分配权限成功')
      // 关闭对话框
      this.setRightdialogVisible = false
    }
  }
}
</script>

<style lang="less" scoped>
.roles-container {
  text-align: left;
}
.el-row {
  text-align: left;
}
.el-tag {
  margin: 10px;
}
.line-bottom {
  border-bottom: 1px solid #ccc;
}
.line-top {
  border-top: 1px solid #ccc;
}
// 纵向居中对齐
.vcenter {
  display: flex;
  align-items: center;
}
</style>
